package cn.xinfei.xdecision.data.core.schduler;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@AllArgsConstructor
public class CustomerScheduledTaskRregistrar implements DisposableBean {

    private TaskScheduler taskScheduler;

    private final Map<String, CustomSchduledTask> scheduledTasks = new ConcurrentHashMap<>(1024);

    public void addTriggerTask(String key, Runnable task, Trigger trigger) {
        if (null == task || null == trigger || StringUtils.isBlank(key)) {
            log.error("任务key和任务线程以及触发器不能为空");
            return;
        }

        CustomSchduledTask customSchduledTask = scheduledTasks.get(key);
        if (null != customSchduledTask) {
            log.info("{}--对应的任务已存在，请勿重复创建", key);
            return;
        }

        //add trigger
        CustomSchduledTask schduledTask = schedulerTriggerTask(new TriggerTask(task, trigger));
        schduledTask.future = this.taskScheduler.schedule(task, trigger);
        scheduledTasks.put(key, schduledTask);
    }


    public void removeTriggerTask(String key) {
        if (StringUtils.isBlank(key)) {
            log.error("key不能为空");
            return;
        }
        CustomSchduledTask schduledTask = scheduledTasks.get(key);
        if (null == schduledTask) {
            log.error("{} --对应的任务不存在，请勿重复删除", key);
        } else {
            log.info("{} --对应的任务取消", key);
            schduledTask.cancel();
            scheduledTasks.remove(key);
        }
    }


    private CustomSchduledTask schedulerTriggerTask(TriggerTask task) {
        return new CustomSchduledTask(task);
    }

    @Override
    public void destroy() {
        for (CustomSchduledTask task : this.scheduledTasks.values()) {
            task.cancel();
        }
    }
}
